package com.wwt.mr;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class InverseStepOne {
    public static class StepOneMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
        @Override
        protected void map(LongWritable key, Text value,Context context) throws IOException, InterruptedException{
            //拿到一行数据
            String line= value.toString();
            //切分各个单词
            String[] fields = StringUtils.split(line," ");
            //获取这一行数据所在的文件切片
            FileSplit inputSplit = (FileSplit)context.getInputSplit();
            //从文件切片中获取文件名字
            String fileName = inputSplit.getPath().getName();
            for(String field:fields){
                //kv封装输出， key: hello-->a.txt v:1 (出现的次数)
                context.write(new Text(field+"-->"+fileName), new LongWritable(1));
            }
        }
    }

    public static class StepOneReducer extends Reducer<Text,LongWritable,Text,LongWritable> {
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values,Context context) throws IOException, InterruptedException {
            //初始化数值
            long counter=0;
            //统计
            for(LongWritable value: values){
                counter+= value.get();
            }
            context.write(key,new LongWritable(counter));
        }

    }

    public static void main(String[] args) throws ClassNotFoundException, IOException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(InverseStepOne.class);

        job.setMapperClass(StepOneMapper.class);
        job.setReducerClass(StepOneReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));//手动指定输入路径
        Path path2 = new Path(args[1]);
        FileSystem fs = path2.getFileSystem(conf);
        if(fs.exists(path2))
        {
            fs.delete(path2, true);//如果存在就删除之前的输出文件路径
        }
        FileOutputFormat.setOutputPath(job,path2);//手动指定输出路径
        System.exit(job.waitForCompletion(true)?0:1);
    }
}
